import HTTP_CODE from '../constant/http-code'
import * as request from '../constant/fetch-request'
import { message } from 'antd'
import { REFRESH_VIDEO, REFRESH_VIDEOS, REFRESH_TOP_VIDEOS, REFRESH_PAGEABLE_VIDEOS } from '../constant/action-type'

const refreshVideos = data => ({
  type: REFRESH_VIDEOS,
  data
})
const refreshVideo = data => ({
  type: REFRESH_VIDEO,
  data
})
const refreshTopVideos = data => ({
  type: REFRESH_TOP_VIDEOS,
  data
})
const refreshPageableVideos = data => ({
  type: REFRESH_PAGEABLE_VIDEOS,
  data
})

export const createVideo = (video,callback) => {
  return () => {
    (async () => {
      const res = await request.post(`./api/videos`, video)
      if (res.status === HTTP_CODE.CREATED) {
        message.success('创建成功')
        callback()
      }
    })()
  }
}

export const getMyVideos = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/videos/my`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshVideos(res.body))
      }
    })()
  }
}
export const getMySubscriptionVideos = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/videos/users/subscriptions`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshVideos(res.body))
      }
    })()
  }
}

export const getTopVideos = () => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/videos/top`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshTopVideos(res.body))
      }
    })()
  }
}

export const getVideoPageable = (current = 1) => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/videos/pageable?page=${--current}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshPageableVideos(res.body))
      }
    })()
  }
}

export const getVideo = id => {
  return dispatch => {
    (async () => {
      const res = await request.get(`./api/videos/${id}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch(refreshVideo(res.body))
      }
    })()
  }
}
export const editVideo = (id, video) => {
  return () => {
    (async () => {
      const res = await request.update(`./api/videos/${id}`, video)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success('编辑成功')
      }
    })()
  }
}

export const deleteVideo = (id) => {
  return dispatch => {
    (async () => {
      const res = await request.del(`./api/videos/${id}`)
      if (res.status === HTTP_CODE.OK) {
        message.success('删除成功')
        dispatch(getMyVideos())
      }
    })()
  }
}
